const Schema = require('async-validator').default;

async function validate(ctx, rules){
    const validator = new Schema(rules);
    let data = {};

    switch(ctx.method){
        case "GET":
        case "DELETE":
            data = ctx.params;
            break;
        case "PUT":
        case "POST":
            data = ctx.request.body || {};
        break;
    }
    return await validator.validate(data).then(() => {
        return data;
    }).catch(err => {
        throw err.errors[0].message;
    })
}

module.exports = validate;